package com.hmall.order.web;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.hmall.common.client.UserFeignClient;
import com.hmall.common.pojo.Address;
import com.hmall.common.pojo.Item;
import com.hmall.common.util.ThreadLocalUtil;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.Params;
import com.hmall.order.service.IOrderService;
import com.hmall.order.service.IOrderServiceDetail;
import com.hmall.order.service.OrderLogisticsService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.hmall.common.client.feignClient;
@RestController
@RequestMapping("order")
public class OrderController {

   @Autowired
   private IOrderService orderService;
   @Autowired
   private feignClient itemFeignClient;
   @Autowired
   private IOrderServiceDetail detail;
   @Autowired
   private UserFeignClient userFeignClient;
   @Autowired
   private OrderLogisticsService orderLogisticsService;


   @GetMapping("{id}")
   public Order queryOrderById(@PathVariable("id") Long orderId) {
      return orderService.getById(orderId);
   }

   @PostMapping
   @GlobalTransactional
   public Long addOrder(@RequestBody Params params){
      long id = IdWorker.getId();
      Order order = new Order();
      order.setId(id);
      Long o = (Long) ThreadLocalUtil.get();
      order.setUserId(o);

      Item item = itemFeignClient.selectById(params.getItemId());
      order.setTotalFee(item.getPrice()*params.getNum());
      order.setStatus(1);
      order.setPaymentType(3);

      orderService.save(order);

      OrderDetail orderDetail = new OrderDetail();
      BeanUtils.copyProperties(order,orderDetail);
      BeanUtils.copyProperties(item,orderDetail);
      orderDetail.setOrderId(order.getId());
      orderDetail.setItemId(item.getId());
      orderDetail.setNum(params.getNum());
      orderDetail.setTitle(item.getName());

      detail.save(orderDetail);

      Address address = userFeignClient.findAddressById(params.getAddressId());
      OrderLogistics orderLogistics = new OrderLogistics();
      BeanUtils.copyProperties(address,orderLogistics);
      orderLogistics.setOrderId(order.getId());
      orderLogistics.setContact(address.getContact());
      orderLogistics.setPhone(address.getMobile());

      orderLogisticsService.save(orderLogistics);
      itemFeignClient.reduce(item.getId(),params.getNum());
       //int i = 1/0;
      return order.getId();
   }


}
